import { cloneDeep } from 'lodash-unified'
import { VxeFormInstance } from 'vxe-table'
import { message } from 'ant-design-vue'
import { useRequest } from 'vue-request'

export type AsycAddOrModifyMethod<T> = (t: T) => Promise<void>

export function useAddModalHook<T>(
  defaultFormData: T,
  asyncModifyMethod: AsycAddOrModifyMethod<T>,
  asyncAddMethod: AsycAddOrModifyMethod<T>,
  $emits: ((evt: 'saveSuc') => void) & ((evt: 'editSuc', val: T) => void)
) {
  const title = ref('新增')
  const formData = ref<T>(cloneDeep(defaultFormData)) as Ref<T>
  const vxeFormRef = ref<VxeFormInstance>()
  const visible = ref<boolean>(false)
  let editMode = false

  const { runAsync: runAdd, loading: addLoading } = useRequest(asyncAddMethod, { manual: true })
  const { runAsync: runModify, loading: modifyLoading } = useRequest(asyncModifyMethod, { manual: true })
  const loading = computed(() => addLoading.value || modifyLoading.value)
  async function onOk() {
    const vxeFormInstance = vxeFormRef.value
    if (!vxeFormInstance) return

    const ret = await vxeFormInstance.validate()
    if (ret !== undefined) return

    if (editMode) {
      await runModify(formData.value)
      $emits('editSuc', cloneDeep(formData.value))
    } else {
      await runAdd(formData.value)
      $emits('saveSuc')
    }
    message.success('操作成功')
    visible.value = false
  }

  function onCancel() {
    visible.value = false
  }

  function onUpdateVxeFormItemStatus(scope: any) {
    const vxeFormInstance = vxeFormRef.value
    if (!vxeFormInstance) return

    vxeFormInstance.updateStatus(scope)
  }
  function onOpenModal(_title: string, initData?: T) {
    title.value = _title
    visible.value = true
    if (initData) {
      editMode = true
      formData.value = cloneDeep(initData)
    } else {
      editMode = false
      formData.value = cloneDeep(defaultFormData)
    }
  }
  return {
    onOk,
    onCancel,
    onUpdateVxeFormItemStatus,
    onOpenModal,
    title,
    vxeFormRef,
    visible,
    loading,
    formData,
  }
}
